package com.example.icongyou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.icongyou.R;
import com.example.icongyou.adapter.CourseAdapter;
import com.example.icongyou.adapter.SemesterSpinnerAdapter;
import com.example.icongyou.api.CourseApi;
import com.example.icongyou.api.StudentCourseApi;
import com.example.icongyou.bean.Course;
import com.example.icongyou.bean.Semester;
import com.example.icongyou.bean.StudentCourseProgress;
import com.example.icongyou.retrofit.RetrofitClient;
import com.example.icongyou.util.UserUtils;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CourseListActivity extends AppCompatActivity {

    private RecyclerView rvCourseList;
    private Spinner spSemester;
    private ProgressBar progressLoading;
    private CourseAdapter courseAdapter;
    private List<Course> courseList = new ArrayList<>();
    private List<StudentCourseProgress> progressList = new ArrayList<>();
    private List<Semester> semesterList = new ArrayList<>();
    private String currentStudentId ; // 实际项目从登录信息获取
    private String lastSelectedSemesterId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_course);

        // 处理系统栏间距
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.layout_course_root), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initViews();
        setupClickListeners();
        loadSemesterData();
    }

    private void initViews() {
        rvCourseList = findViewById(R.id.rv_course_list);
        spSemester = findViewById(R.id.sp_semester);
        progressLoading = findViewById(R.id.progress_loading);
        rvCourseList.setLayoutManager(new GridLayoutManager(this, 2));
    }

    private void setupClickListeners() {
        // 学期筛选下拉框监听（添加防抖处理）
        spSemester.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (!semesterList.isEmpty()) {
                    Semester selected = semesterList.get(position);
                    if (!selected.getSemesterId().equals(lastSelectedSemesterId)) {
                        lastSelectedSemesterId = selected.getSemesterId();
                        loadCoursesBySemester(lastSelectedSemesterId);
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    // 加载学期列表
    private void loadSemesterData() {
        CourseApi api = RetrofitClient.getInstance().create(CourseApi.class);
        api.getAllSemesters().enqueue(new Callback<List<Semester>>() {
            @Override
            public void onResponse(Call<List<Semester>> call, Response<List<Semester>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    semesterList = response.body();
                    spSemester.setAdapter(new SemesterSpinnerAdapter(
                            CourseListActivity.this, semesterList));
                    // 默认选中最新学期（按时间排序取最后一个）
                    if (!semesterList.isEmpty()) {
                        spSemester.setSelection(semesterList.size() - 1);
                    }
                } else {
                    showToast("获取学期失败");
                }
            }

            @Override
            public void onFailure(Call<List<Semester>> call, Throwable t) {
                showToast("网络错误：" + t.getMessage());
            }
        });
    }

    // 按学期加载课程
    private void loadCoursesBySemester(String semesterId) {
        showLoading();
        // 调用新增的接口，获取学生该学期已选课程
        StudentCourseApi api = RetrofitClient.getStudentCourseApi();
        String currentStudentId = UserUtils.getCurrentStudentId(this);
        api.getEnrolledCourses(currentStudentId, semesterId)
                .enqueue(new Callback<List<Course>>() {
                    @Override
                    public void onResponse(Call<List<Course>> call, Response<List<Course>> response) {
                        hideLoading();
                        if (response.isSuccessful() && response.body() != null) {
                            courseList = response.body();
                            loadCourseProgress(); // 加载进度后刷新列表
                        } else {
                            Toast.makeText(CourseListActivity.this, "获取课程失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<List<Course>> call, Throwable t) {
                        hideLoading();
                        Toast.makeText(CourseListActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    // 加载课程进度
    private void loadCourseProgress() {
        progressList.clear();
        CourseApi api = RetrofitClient.getInstance().create(CourseApi.class);
        int totalCourses = courseList.size();
        int[] loadedCount = {0}; // 用数组包裹，允许匿名类修改

        String currentStudentId = UserUtils.getCurrentStudentId(this);
        for (Course course : courseList) {
            api.getCourseProgress(course.getCourseId(), currentStudentId)
                    .enqueue(new Callback<StudentCourseProgress>() {
                        @Override
                        public void onResponse(Call<StudentCourseProgress> call,
                                               Response<StudentCourseProgress> response) {
                            loadedCount[0]++;
                            if (response.isSuccessful() && response.body() != null) {
                                progressList.add(response.body());
                            } else {
                                // 进度获取失败时使用默认值
                                progressList.add(new StudentCourseProgress(
                                        "default_" + course.getCourseId(),
                                        currentStudentId,
                                        course.getCourseId(),
                                        0, 0.0, ""
                                ));
                            }
                            if (loadedCount[0] == totalCourses) {
                                setupAdapter();
                            }
                        }

                        @Override
                        public void onFailure(Call<StudentCourseProgress> call, Throwable t) {
                            loadedCount[0]++;

                            progressList.add(new StudentCourseProgress(
                                    "default_" + course.getCourseId(),
                                    currentStudentId,
                                    course.getCourseId(),
                                    0, 0.0, ""
                            ));
                            if (loadedCount[0] == totalCourses) {
                                setupAdapter();
                            }
                        }
                    });
        }
    }

    // 设置课程适配器
    private void setupAdapter() {
        courseAdapter = new CourseAdapter(courseList, progressList, course -> {
            // 跳转到课程详情页（添加动画）
            Intent intent = new Intent(CourseListActivity.this, CourseDetailActivity.class);
            intent.putExtra("course", course); // 传递完整课程对象
            startActivity(intent);
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        });
        rvCourseList.setAdapter(courseAdapter);
    }

    // 显示加载状态
    private void showLoading() {
        progressLoading.setVisibility(View.VISIBLE);
        rvCourseList.setVisibility(View.GONE);
    }

    // 隐藏加载状态
    private void hideLoading() {
        progressLoading.setVisibility(View.GONE);
        rvCourseList.setVisibility(View.VISIBLE);
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}